package com.manuelvs.bobbysadventure;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.SpriteBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class BluetoothLogic extends BaseGameActivity implements IUpdateHandler, IOnSceneTouchListener{
    // Debugging
    static final String TAG = "BluetoothChat";
    static final boolean D = false;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    static final int REQUEST_CONNECT_DEVICE = 1;
    public static final int REQUEST_ENABLE_BT = 2;

    // Name of the connected device
    String mConnectedDeviceName = null;
    // String buffer for outgoing messages

    
    float touchX;
	float touchY;
    int isserver;
	
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;
    
    private bobby _bazul;
    private bobby _brojo;
    
	private Camera mCamera;

    private BitmapTextureAtlas mBitmapTextureAtlas;
    private TiledTextureRegion bobbymovement;
    private TiledTextureRegion bobbymovement2;

    private TextureRegion Campo;

    private Scene mMainScene;

    AnimatedSprite sbobbymovement;
    AnimatedSprite sbobbymovement2;
    
    String message2send;
    String Width;
    String Height;
    String operation;
    
    private BitmapTextureAtlas mFontTexture;
    private Font mFont;
    
    ChangeableText score;
    
    boolean killstarted=false;
    boolean remotekillstarted=false;
    char counter=0;
    char remotecounter=0;
    
	@Override
	public Engine onLoadEngine()
	{
        Bundle bundle = getIntent().getExtras();
        isserver=bundle.getInt("isserver");
		mCamera = new Camera(0, 0, 480, 320);
		return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,new RatioResolutionPolicy(480, 320), mCamera));
	}
	
	@Override
	public void onLoadResources()
	{
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		this.mBitmapTextureAtlas = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR);
        this.bobbymovement = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "bobbysmovement.png", 0, 0, 6, 6);
        this.bobbymovement2 = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "bobbysmovementrojo.png", 301, 0, 6, 6);
        this.Campo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "campo.png", 0, 361);
        this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas);
        
        this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

        this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.BLACK);

        this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
        this.mEngine.getFontManager().loadFont(mFont);

	}
	@Override
	public Scene onLoadScene()
	{
		_brojo._Width=270;
		_brojo._height=149;
		_bazul._Width=130;
		_bazul._height=149;
	    mMainScene = new Scene();
	    score = new ChangeableText(205, 0, this.mFont, Integer.toString(_bazul.score) + " " + "-" + " " + Integer.toString(_brojo.score), 7);
	    mMainScene.attachChild(score);
	    
		SpriteBackground bg = new SpriteBackground(new Sprite(0, 0, Campo));
		mMainScene.setBackground(bg);
	    

	    sbobbymovement = new AnimatedSprite(_bazul._Width, _bazul._height, bobbymovement);
	    sbobbymovement.animate(new long[] {30}, new int[] {18}, 30);
	    mMainScene.attachChild(sbobbymovement);
	    sbobbymovement.setScale(0.5f);
	    
	    sbobbymovement2 = new AnimatedSprite(_brojo._Width, _brojo._height, bobbymovement2);
	    sbobbymovement2.animate(new long[] {30}, new int[] {18}, 30);
	    mMainScene.attachChild(sbobbymovement2);
	    sbobbymovement2.setScale(0.5f);
	    
	    mMainScene.registerUpdateHandler(this);
	    mMainScene.setOnSceneTouchListener(this);
	    
	    return mMainScene;
	}

	@Override
	public void onLoadComplete() {}
	@Override
	public void onUpdate(float secondsSinceLastLoop)
	{
		/*if(mChatService.getState()==3)*/ movebobby(secondsSinceLastLoop);
		score.setText(Integer.toString(_bazul.score) + " " + "-" + " " + Integer.toString(_brojo.score));
		
	}
	private void movebobby(float secondsSinceLastLoop)
	{
		if(_bazul.isJumping()) _bazul.jump();
		if(_brojo.isJumping()) _brojo.jump();
		_bazul.move(secondsSinceLastLoop);
		_brojo.move(secondsSinceLastLoop);
		sbobbymovement.animate(new long[] {30}, new int[] {_bazul.animate}, 30);
		sbobbymovement.setPosition(_bazul._Width, _bazul._height);
		sbobbymovement2.animate(new long[] {30}, new int[] {_brojo.animate}, 30);
		sbobbymovement2.setPosition(_brojo._Width, _brojo._height);
		
		if((_bazul.kill && sbobbymovement2.collidesWith(sbobbymovement)) || killstarted)
		{
			counter++;
			if(counter>20)
			{
				killstarted=true;
				sbobbymovement2.setPosition(_brojo._Width, _brojo._height+11);
				sbobbymovement2.setRotation(90);
				sbobbymovement2.animate(new long[] {30}, new int[] {9}, 30);
			}
			if(counter==40)
			{
				counter=0;
				_brojo._Width=270;
				_brojo._height=149;
				_bazul.kill=false;
				_bazul.score++;
				sbobbymovement2.setRotation(0);
				killstarted=false;
			}
		}
		if(_bazul.kill && !sbobbymovement2.collidesWith(sbobbymovement))
		{
			_bazul.kill=false;
		}
		if((_brojo.kill && sbobbymovement2.collidesWith(sbobbymovement)) || remotekillstarted)
		{
			remotecounter++;
			if(remotecounter>20)
			{
				remotekillstarted=true;
				sbobbymovement.setPosition(_bazul._Width, _bazul._height+11);
				sbobbymovement.setRotation(90);
				sbobbymovement.animate(new long[] {30}, new int[] {9}, 30);
			}
			if(remotecounter==40)
			{
				remotecounter=0;
				_bazul._Width=130;
				_bazul._height=149;
				_brojo.kill=false;
				_brojo.score++;
				sbobbymovement.setRotation(0);
				remotekillstarted=false;
			}
		}
		if(_brojo.kill && !sbobbymovement2.collidesWith(sbobbymovement))
		{
			_brojo.kill=false;
		}
	}
	
    @Override
    public boolean onSceneTouchEvent(Scene scene, TouchEvent touchEvent)
    {
    	touchX=touchEvent.getX();
    	touchY=touchEvent.getY();
    	if(isserver==0)
    	{
	  		  if (touchEvent.isActionDown())
	  		  {
	  	    	if(touchY>260&&touchX<420&&touchX>60)
	  	    		_brojo.operation=3;
		    	if(touchY>260 && touchX<60)
		    		_brojo.operation=8;
		    	if(touchY>260 && touchX>420)
		    		_brojo.operation=9;
		    	if(touchY<60&&touchX<420&&touchX>60)
		    		_brojo.operation=4;
		    	if(touchX<60&&touchY<260&&touchY>60)
		    		_brojo.operation=2;
		    	if(touchX>420&&touchY<260&&touchY>60)
		    		_brojo.operation=1;
		    	if((touchX>420)&&(touchY<60))
		    		_brojo.operation=5;
		    	if((touchX<60)&&(touchY<60))
		    		_brojo.operation=6;
		    	if(touchX>60 && touchX<420 && touchY>60 &&touchY<260)
		    		_brojo.operation=7;
	  		  }
	  		  
			if (touchEvent.isActionUp())
			{
				_brojo.operation=0;
			}
			message2send="";
			message2send +=_brojo._Width;
			if(_brojo._Width<100) message2send +=" ";
			if(_brojo._Width<10 && _brojo._Width>-1) message2send +=" ";
			message2send +=(int)_brojo._height;
			if(_brojo._height<100) message2send +=" ";
			if(_brojo._height<10 && _brojo._height>-1) message2send +=" ";
			message2send +=_brojo.operation;
			sendMessage(message2send);
			

    	}
    	if(isserver==1)
    	{
	  		  if (touchEvent.isActionDown())
	  		  {
	  	    	if(touchY>260&&touchX<420&&touchX>60)
	  	    		_bazul.operation=3;
		    	if(touchY>260 && touchX<60)
		    		_bazul.operation=8;
		    	if(touchY>260 && touchX>420)
		    		_bazul.operation=9;
		    	if(touchY<60&&touchX<420&&touchX>60)
		    		_bazul.operation=4;
		    	if(touchX<60&&touchY<260&&touchY>60)
		    		_bazul.operation=2;
		    	if(touchX>420&&touchY<260&&touchY>60)
		    		_bazul.operation=1;
		    	if((touchX>420)&&(touchY<60))
		    		_bazul.operation=5;
		    	if((touchX<60)&&(touchY<60))
		    		_bazul.operation=6;
		    	if(touchX>60 && touchX<420 && touchY>60 &&touchY<260)
		    		_bazul.operation=7;
	  		  }
	  		  
			if (touchEvent.isActionUp())
			{
				_bazul.operation=0;
			}
			message2send="";
			message2send +=_bazul._Width;
			if(_bazul._Width<100) message2send +=" ";
			if(_bazul._Width<10 && _bazul._Width>-1) message2send +=" ";
			message2send +=(int)_bazul._height;
			if(_bazul._height<100) message2send +=" ";
			if(_bazul._height<10 && _bazul._height>-1) message2send +=" ";
			message2send +=_bazul.operation;
			sendMessage(message2send);
			
    	}
		
		return true;
    }

	@Override
	public void reset() {}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _bazul = new bobby();
        _brojo = new bobby();
        if(D) Log.e(TAG, "+++ ON CREATE +++");
        // Set up the window layout
        

        
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        
        
    }
    
    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) 
            {
            	setupChat();
            }
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }

    private void setupChat() {
        Log.d(TAG, "setupChat()");
        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);
        ensureDiscoverable();
        if(isserver==1)
        {
	        Intent serverIntent = new Intent(this, DeviceListActivity.class);
	        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
        }
        // Initialize the buffer for outgoing messages
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }

    void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    public void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            //Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() == 7) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);  //enviar ancho, alto y operation

        }
    }

    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                //Log.d("ADebugTag1","readMessage: " + readMessage);
                if(isserver==0)
                {
                	Width=readMessage.substring(0, 3);
                	Height=readMessage.substring(3, 6);
                	operation=readMessage.substring(6);
                	_bazul._Width=Integer.parseInt(Width.trim());
                	_bazul._height=Integer.parseInt(Height.trim());
                	_bazul.operation=Integer.parseInt(operation.trim());
                }
                if(isserver==1)
                {
                	Width=readMessage.substring(0, 3);
                	Height=readMessage.substring(3, 6);
                	operation=readMessage.substring(6);
                	_brojo._Width=Integer.parseInt(Width.trim());
                	_brojo._height=Integer.parseInt(Height.trim());
                	_brojo.operation=Integer.parseInt(operation.trim());
                }
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
   
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mChatService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupChat();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        }
        return false;
        
    }

   
}

